//
//  HMDesignRefreshView.swift
//  swift微博项目
//
//  Created by huodian on 16/10/2.
//  Copyright © 2016年 huodian. All rights reserved.
//

import UIKit

enum DragingStatues:Int {
   
    case Normall
    
    case Pulling
    
    case Refreshing
}

let topViewHeight: CGFloat = 50


class HMDesignRefreshView: UIControl {
    
    
    var refreshing : DragingStatues = .Normall {
        didSet{
            
            
            switch refreshing
            {
                
                
            case .Normall:
            tipLable.text  = "下拉起飞"
            
         self.arrowItem.isHidden = false
            
            self.activityView.stopAnimating()
          
            self.arrowItem.isHidden = false
            
            if oldValue == .Refreshing {
                //添加恢复时的动画
                UIView.animate(withDuration: 0.5, animations: { 
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - topViewHeight
                })
           
                
            }
            
            
                UIView.animate(withDuration: 0.5, animations: { 
                    
                    self.arrowItem.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
                
                
            case .Pulling:
                tipLable.text = "准备起飞"
                
                  self.activityView.stopAnimating()
            
                
                UIView.animate(withDuration: 0.5, animations: { 
                    
                    self.arrowItem.transform = CGAffineTransform.identity
                })
                
            case .Refreshing:
                tipLable.text = "正在飞"
                
                self.arrowItem.isHidden = true
                
                activityView.startAnimating()
                
                self.scrollView!.contentInset.top =
                    self.scrollView!.contentInset.top + topViewHeight
               // self.activityView.isHidden = false
                
            }
            
        }
        
        
    }
    

//解决刷新动画延迟问题
    func stopAnimation(){
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { 
            
            self.refreshing = .Normall
            
        }
        
    }
    
    override init(frame: CGRect) {
        
        
        let rect  = CGRect(x: 0, y: -50, width: UIScreen.main.bounds.size.width, height: 50)
        
        
        super.init(frame: rect)
        
        self.backgroundColor = random()
        
        setupUI()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //当控件的父控件改变的时候调用此方法
    override func willMove(toSuperview newSuperview: UIView?) {
        
        super.willMove(toSuperview: newSuperview)
      
        
        if let fartherView = newSuperview as? UIScrollView {
            
        self.scrollView = fartherView
            
            
        fartherView.addObserver(self, forKeyPath: "contentOffset", options:.new, context: nil)
            
        }
        
        
    }
    
    
    //kvo中必须实现此方法,否则报错
    
  override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let offset = scrollView?.contentOffset.y ?? 0
        
        let normall : CGFloat = -114
        
        
        if scrollView!.isDragging {
            // 手动拽动过程
            if offset <  normall && refreshing == .Normall {
                //拽动到导航栏以下
                
                refreshing = .Pulling
                
                
            }else if offset > normall && refreshing == .Pulling
            {
                //和导航栏重叠
                refreshing = .Normall
                
            }
            
        }else{
            
            //松手之后,刷新过程
            if refreshing == .Pulling {
                
                  refreshing = .Refreshing
                
                self.sendActions(for: UIControlEvents.valueChanged)
            }
            
          
            
        }
        
        
        
    }
    
    func setupUI(){
        
        self.addSubview(tipLable)
        
        self.addSubview(activityView)
        
        self.addSubview(arrowItem)
        
        tipLable.snp.makeConstraints { (make ) in
            make.centerX.equalTo(self.snp.centerX).offset(10)
            
            make.centerY.equalTo(self.snp.centerY)
        }
        
        activityView.snp.makeConstraints {(make) in
            
            make.centerX.equalTo(tipLable.snp.leading).offset(-10)
            
            make.centerY.equalTo(self.snp.centerY)
            
        }
        
        arrowItem.snp.makeConstraints { (make ) in
            make.center.equalTo(activityView.snp.center)
        }
   
        
    }
    
    
    var scrollView : UIScrollView?
    
    
    lazy var arrowItem :UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    lazy var tipLable : UILabel = UILabel(title: "下拉刷新", font: 14, corlor: UIColor.gray)
    
    lazy var activityView : UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
 
    deinit {
        
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
